// 多站点popup管理
class MultiSitePopupManager {
  constructor() {
    this.configManager = new SiteConfigManager();
    this.hasDetectedSite = false; // 标记是否已经检测到站点
    this.refreshInterval = null; // 存储刷新定时器
    this.init();
  }

  async init() {
    console.log('[Multi-Site Token Export] Popup初始化开始');
    
    try {
      console.log('[Multi-Site Token Export] 步骤1: 加载站点配置');
      await this.loadSites();
      console.log('[Multi-Site Token Export] 步骤2: 加载扩展配置');
      await this.loadConfig();
      console.log('[Multi-Site Token Export] 步骤3: 绑定事件');
      this.bindEvents();
      
      console.log('[Multi-Site Token Export] 步骤4: 获取状态');
      // 立即获取状态（在用户点击扩展图标时，background脚本应该已经准备好）
      this.getStatus();
      
      // 延迟500ms后再获取一次，确保能捕获到content-script发送的token
      setTimeout(() => {
        console.log('[Multi-Site Token Export] 延迟500ms后再次获取状态');
        this.getStatus();
      }, 500);
      
      console.log('[Multi-Site Token Export] Popup初始化完成');
    } catch (error) {
      console.error('[Multi-Site Token Export] Popup初始化出错:', error);
    }
    
    // 设置定期刷新，确保时间戳实时更新
    this.refreshInterval = setInterval(() => {
      if (!this.hasDetectedSite) {
        console.log('[Multi-Site Token Export] 尚未检测到站点，继续刷新');
        this.getStatus();
      } else {
        console.log('[Multi-Site Token Export] 已检测到站点，停止循环刷新');
        this.stopPeriodicRefresh();
      }
    }, 2000); // 每2秒刷新一次
    
    // 监听来自content-script的刷新通知
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      if (message.action === 'refreshPopup') {
        console.log('[Multi-Site Token Export] 收到刷新通知，立即更新状态');
        this.getStatus();
        sendResponse({ success: true });
      }
    });
  }

  async loadSites() {
    // 只从本地存储获取站点配置，不包含时间戳
    const sites = await this.configManager.getSites();
    this.renderSites(sites);
  }

  renderSites(sites) {
    const sitesList = document.getElementById('sitesList');
    sitesList.innerHTML = '';

    sites.forEach(site => {
      const siteItem = document.createElement('div');
      siteItem.className = `site-item ${site.enabled ? 'site-enabled' : 'site-disabled'}`;
      siteItem.setAttribute('data-domain', site.site_domain);
      
      // 处理时间戳，如果不存在则显示"从未导出"
      const lastExportTime = site.lastExportTime || null;
      
      siteItem.innerHTML = `
        <div class="site-info">
          <div class="site-name">${site.site_name} （${site.site_domain}）</div>
          <div class="site-auth">${site.auth_type} → ${site.auth_key}</div>
          <div class="site-last-export">最后导出时间：${this.formatLastExportTime(lastExportTime)}</div>
        </div>
        <div class="site-actions">
          <button class="button small edit-btn" data-domain="${site.site_domain}" title="编辑">
            ✎
          </button>
          <button class="button small toggle-btn" data-domain="${site.site_domain}" title="${site.enabled ? '禁用' : '启用'}">
            ${site.enabled ? '⏸' : '▶'}
          </button>
          <button class="button small danger delete-btn" data-domain="${site.site_domain}" title="删除">
            ✕
          </button>
        </div>
      `;
      
      sitesList.appendChild(siteItem);
    });

    // 重新绑定事件
    this.bindSiteEvents();
  }

  bindSiteEvents() {
    // 绑定编辑按钮事件
    document.querySelectorAll('.edit-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const domain = e.target.getAttribute('data-domain');
        this.editSite(domain);
      });
    });

    // 绑定切换按钮事件
    document.querySelectorAll('.toggle-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const domain = e.target.getAttribute('data-domain');
        this.toggleSite(domain);
      });
    });

    // 绑定删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const domain = e.target.getAttribute('data-domain');
        this.deleteSite(domain);
      });
    });
  }

  async toggleSite(domain) {
    const sites = await this.configManager.getSites();
    const site = sites.find(s => s.site_domain === domain);
    if (site) {
      const newEnabled = !site.enabled;
      await this.configManager.updateSite(domain, { enabled: newEnabled });
      
      // 更新界面显示
      const siteItem = document.querySelector(`[data-domain="${domain}"]`)?.closest('.site-item');
      if (siteItem) {
        // 更新CSS类
        siteItem.className = `site-item ${newEnabled ? 'site-enabled' : 'site-disabled'}`;
        
        // 更新按钮文本和图标
        const toggleBtn = siteItem.querySelector('.toggle-btn');
        if (toggleBtn) {
          toggleBtn.textContent = newEnabled ? '⏸' : '▶';
          toggleBtn.title = newEnabled ? '禁用' : '启用';
        }
      }
      
      console.log(`站点 ${domain} 已${newEnabled ? '启用' : '禁用'}`);
    }
  }

  async deleteSite(domain) {
    if (confirm('确定要删除这个站点吗？')) {
      await this.configManager.deleteSite(domain);
      await this.loadSites();
    }
  }

  async editSite(domain) {
    const sites = await this.configManager.getSites();
    const site = sites.find(s => s.site_domain === domain);
    if (site) {
      // 填充编辑表单
      document.getElementById('editSiteName').value = site.site_name;
      document.getElementById('editSiteDomain').value = site.site_domain;
      document.getElementById('editAuthType').value = site.auth_type;
      document.getElementById('editAuthKey').value = site.auth_key;
      
      // 显示编辑表单，隐藏添加表单和按钮
      document.getElementById('editSiteForm').style.display = 'block';
      document.getElementById('addSiteForm').style.display = 'none';
      document.getElementById('showAddForm').style.display = 'none';
      
      // 存储当前编辑的域名
      this.editingDomain = domain;
    }
  }

  async saveEdit() {
    const siteName = document.getElementById('editSiteName').value.trim();
    const siteDomain = document.getElementById('editSiteDomain').value.trim();
    const authType = document.getElementById('editAuthType').value;
    const authKey = document.getElementById('editAuthKey').value.trim();

    // 检查具体缺失的字段
    const missingFields = [];
    if (!siteName) missingFields.push('站点名称');
    if (!siteDomain) missingFields.push('域名');
    if (!authKey) missingFields.push('认证字段名');
    
    if (missingFields.length > 0) {
      alert(`请填写以下字段：\n${missingFields.join('、')}`);
      return;
    }

    try {
      // 如果域名改变了，需要先删除旧的
      if (this.editingDomain !== siteDomain) {
        await this.configManager.deleteSite(this.editingDomain);
      // 添加新的站点配置
      await this.configManager.addSite({
        site_name: siteName,
        site_domain: siteDomain,
        auth_type: authType,
        auth_key: authKey,
        description: `从${authType}获取${authKey}`
      });
      } else {
        // 域名没变，直接更新现有站点
        await this.configManager.updateSite(this.editingDomain, {
          site_name: siteName,
          site_domain: siteDomain,
          auth_type: authType,
          auth_key: authKey,
          description: `从${authType}获取${authKey}`
        });
      }

      // 隐藏编辑表单，显示添加按钮
      document.getElementById('editSiteForm').style.display = 'none';
      document.getElementById('addSiteForm').style.display = 'none';
      document.getElementById('showAddForm').style.display = 'block';

      await this.loadSites();
      alert('站点修改成功！');
    } catch (error) {
      alert('修改站点失败: ' + error.message);
    }
  }

  cancelEdit() {
    // 清空编辑表单
    document.getElementById('editSiteName').value = '';
    document.getElementById('editSiteDomain').value = '';
    document.getElementById('editAuthType').value = 'localStorage';
    document.getElementById('editAuthKey').value = '';
    
    // 隐藏编辑表单，显示添加按钮
    document.getElementById('editSiteForm').style.display = 'none';
    document.getElementById('addSiteForm').style.display = 'none';
    document.getElementById('showAddForm').style.display = 'block';
    
    // 清空编辑状态
    this.editingDomain = null;
  }

  showAddForm() {
    // 自动填充当前网页信息
    this.autoFillCurrentSite();
    
    // 显示添加表单
    document.getElementById('addSiteForm').style.display = 'block';
    document.getElementById('showAddForm').style.display = 'none';
  }

  autoFillCurrentSite() {
    try {
      // 获取当前标签页信息
      chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
        if (tabs[0]) {
          const url = new URL(tabs[0].url);
          const hostname = url.hostname;
          
          // 自动填充域名
          document.getElementById('siteDomain').value = hostname;
          
          // 尝试从页面标题提取站点名称
          const title = tabs[0].title;
          if (title) {
            // 提取标题中的主要部分作为站点名称
            const siteName = title.split(' - ')[0].split(' | ')[0].trim();
            if (siteName && siteName.length > 0) {
              document.getElementById('siteName').value = siteName;
            }
          }
        }
      });
    } catch (error) {
      console.log('无法获取当前页面信息:', error);
    }
  }

  async addSite() {
    const siteName = document.getElementById('siteName').value.trim();
    const siteDomain = document.getElementById('siteDomain').value.trim();
    const authType = document.getElementById('authType').value;
    const authKey = document.getElementById('authKey').value.trim();

    // 检查具体缺失的字段
    const missingFields = [];
    if (!siteName) missingFields.push('站点名称');
    if (!siteDomain) missingFields.push('域名');
    if (!authKey) missingFields.push('认证字段名');
    
    if (missingFields.length > 0) {
      alert(`请填写以下字段：\n${missingFields.join('、')}`);
      return;
    }

    try {
      await this.configManager.addSite({
        site_name: siteName,
        site_domain: siteDomain,
        auth_type: authType,
        auth_key: authKey,
        description: `从${authType}获取${authKey}`
      });

      // 清空表单
      document.getElementById('siteName').value = '';
      document.getElementById('siteDomain').value = '';
      document.getElementById('authKey').value = '';

      // 隐藏添加表单，显示添加按钮
      document.getElementById('addSiteForm').style.display = 'none';
      document.getElementById('showAddForm').style.display = 'block';

      await this.loadSites();
      alert('站点添加成功！');
    } catch (error) {
      alert('添加站点失败: ' + error.message);
    }
  }

  async loadConfig() {
    const result = await chrome.storage.local.get(['apiUrl', 'retryCount', 'retryDelay']);
    document.getElementById('configApiUrl').value = result.apiUrl || 'http://dev.com/multi-site-token-receiver.php';
    document.getElementById('configRetryCount').value = result.retryCount || 2;
    document.getElementById('configRetryDelay').value = (result.retryDelay || 5000) / 1000;
  }

  async saveConfig() {
    const apiUrl = document.getElementById('configApiUrl').value.trim();
    const retryCount = parseInt(document.getElementById('configRetryCount').value);
    const retryDelay = parseInt(document.getElementById('configRetryDelay').value) * 1000;
  
  if (!apiUrl) {
      alert('请填写服务地址');
      return;
    }
    
    // 获取保存按钮并显示加载状态
    const saveBtn = document.getElementById('saveConfig');
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '检测连接中...';
    saveBtn.disabled = true;
    
    try {
      // 先进行连通性检测
      const connectionResult = await this.testConnection(apiUrl);
      
      if (!connectionResult.success) {
        alert('❌ 连接测试失败：' + (connectionResult.error || '无法连接到服务器'));
        saveBtn.textContent = originalText;
        saveBtn.disabled = false;
    return;
  }
  
      // 连接成功，保存配置
      saveBtn.textContent = '保存中...';
      
      await chrome.storage.local.set({
        apiUrl: apiUrl,
        retryCount: retryCount,
        retryDelay: retryDelay
      });

      // 通知后台脚本更新配置
      chrome.runtime.sendMessage({ 
        action: 'updateConfig', 
        config: { apiUrl, retryCount, retryDelay } 
      });

      alert('✅ 配置保存成功！连接测试通过');
      this.getStatus();
    } catch (error) {
      alert('保存配置失败: ' + error.message);
    } finally {
      saveBtn.textContent = originalText;
      saveBtn.disabled = false;
    }
  }

  async testConnection(apiUrl = null) {
    return new Promise((resolve) => {
      chrome.runtime.sendMessage({ 
        action: 'testConnection',
        apiUrl: apiUrl 
      }, (response) => {
        if (chrome.runtime.lastError) {
          resolve({ success: false, error: chrome.runtime.lastError.message });
        } else if (response && response.success) {
          resolve({ success: true });
        } else {
          resolve({ success: false, error: response?.error || '未知错误' });
        }
      });
    });
  }

  testDataExtraction() {
    const testBtn = document.getElementById('testDataExtraction');
    const originalText = testBtn.textContent;
    
    testBtn.textContent = '测试中...';
    testBtn.disabled = true;
    
    // 获取当前表单数据
    const siteName = document.getElementById('siteName').value.trim();
    const siteDomain = document.getElementById('siteDomain').value.trim();
    const authType = document.getElementById('authType').value;
    const authKey = document.getElementById('authKey').value.trim();

    // 检查具体缺失的字段
    const missingFields = [];
    if (!siteName) missingFields.push('站点名称');
    if (!siteDomain) missingFields.push('域名');
    if (!authKey) missingFields.push('认证字段名');
    
    if (missingFields.length > 0) {
      alert(`请填写以下字段：\n${missingFields.join('、')}`);
      testBtn.textContent = originalText;
      testBtn.disabled = false;
      return;
    }

    // 创建临时站点配置进行测试
    const tempSite = {
      site_name: siteName,
      site_domain: siteDomain,
      auth_type: authType,
      auth_key: authKey
    };

    try {
      const token = AuthDataExtractor.extract(tempSite);
      
      if (token) {
        alert(`✅ 数据提取成功！\n\n提取到的Token:\n${token.substring(0, 50)}${token.length > 50 ? '...' : ''}\n\n长度: ${token.length} 字符`);
      } else {
        alert('❌ 数据提取失败！\n\n可能的原因：\n1. 认证字段名不正确\n2. 当前页面没有该数据\n3. 数据格式不匹配');
      }
    } catch (error) {
      alert('❌ 数据提取出错：' + error.message);
    }

    testBtn.textContent = originalText;
    testBtn.disabled = false;
  }

  getStatusWithSimpleRetry() {
    chrome.runtime.sendMessage({ action: 'getStatus' }, (response) => {
      if (response) {
        console.log('[Multi-Site Token Export] 收到状态响应:', response);
        this.handleStatusResponse(response);
      } else {
        console.log('[Multi-Site Token Export] 第一次获取状态失败，1秒后重试');
        setTimeout(() => {
          chrome.runtime.sendMessage({ action: 'getStatus' }, (response) => {
            if (response) {
              console.log('[Multi-Site Token Export] 重试成功收到状态响应:', response);
              this.handleStatusResponse(response);
            } else {
              console.log('[Multi-Site Token Export] 重试失败，使用本地配置检测');
              this.detectCurrentSiteFromLocalConfig().then(detectedSite => {
                if (detectedSite && !this.hasDetectedSite) {
                  this.hasDetectedSite = true;
                  console.log('[Multi-Site Token Export] 从本地配置检测到站点，将停止循环刷新');
                }
              });
            }
          });
        }, 1000);
      }
    });
  }

  getStatus() {
    console.log('[Multi-Site Token Export] getStatus方法被调用');
    
    // 检查DOM元素是否存在
    const currentSiteElement = document.getElementById('currentSite');
    console.log('[Multi-Site Token Export] currentSite元素:', currentSiteElement);
    
    if (!currentSiteElement) {
      console.error('[Multi-Site Token Export] currentSite元素不存在！');
      return;
    }
    
    // 当用户点击扩展图标时，立即显示"正在获取状态..."而不是"检测中..."
    currentSiteElement.textContent = '正在获取状态...';
    console.log('[Multi-Site Token Export] 已设置显示文本为"正在获取状态..."');
    
    console.log('[Multi-Site Token Export] 发送消息到background脚本');
    chrome.runtime.sendMessage({ action: 'getStatus' }, (response) => {
      console.log('[Multi-Site Token Export] 收到background响应:', response);
      console.log('[Multi-Site Token Export] chrome.runtime.lastError:', chrome.runtime.lastError);
      if (response) {
        console.log('[Multi-Site Token Export] 收到状态响应:', response);
        const apiUrl = response.apiUrl || 'http://dev.com/multi-site-token-receiver.php';
        const apiUrlElement = document.getElementById('apiUrl');
        
        // 设置完整URL到title属性
        apiUrlElement.title = apiUrl;
        
        // 显示简化的URL
        if (apiUrl.length > 35) {
          try {
            const url = new URL(apiUrl);
            const domain = url.hostname;
            const path = url.pathname;
            const search = url.search;
            
            // 构建显示字符串
            let displayUrl = domain;
            
            // 添加路径（如果不太长）
            if (path && path !== '/') {
              if (path.length <= 20) {
                displayUrl += path;
              } else {
                displayUrl += path.substring(0, 17) + '...';
              }
            }
            
            // 添加查询参数（如果存在且不太长）
            if (search && search.length <= 15) {
              displayUrl += search;
            }
            
            // 如果总长度仍然太长，进一步截断
            if (displayUrl.length > 35) {
              displayUrl = domain + '/...';
            }
            
            apiUrlElement.textContent = displayUrl;
          } catch (error) {
            // 如果URL解析失败，显示前35个字符
            apiUrlElement.textContent = apiUrl.substring(0, 35) + '...';
          }
        } else {
          apiUrlElement.textContent = apiUrl;
        }
        
        document.getElementById('retryConfig').textContent = `${response.retryCount || 2}次重试，间隔${(response.retryDelay || 3000) / 1000}秒`;
        
        // 只更新状态信息，不重新渲染站点列表
        // 获取当前标签页信息来检测站点
        this.detectCurrentSite(response.sites);
        
        // 更新站点列表中的时间戳（如果数据包含时间戳）
        if (response.sites) {
          this.updateSiteTimestamps(response.sites);
        }
      } else {
        console.log('[Multi-Site Token Export] 第一次获取状态失败，立即重试');
        console.log('[Multi-Site Token Export] 失败原因:', chrome.runtime.lastError);
        
        // 如果第一次失败，立即重试一次（用户刚点击图标，background脚本应该马上就绪）
        setTimeout(() => {
          console.log('[Multi-Site Token Export] 执行重试');
          chrome.runtime.sendMessage({ action: 'getStatus' }, (response) => {
            console.log('[Multi-Site Token Export] 重试收到background响应:', response);
            console.log('[Multi-Site Token Export] 重试chrome.runtime.lastError:', chrome.runtime.lastError);
            
            if (response) {
              console.log('[Multi-Site Token Export] 重试成功收到状态响应:', response);
              this.handleStatusResponse(response);
            } else {
              console.log('[Multi-Site Token Export] 重试失败，使用本地配置检测');
              this.detectCurrentSiteFromLocalConfig().then(detectedSite => {
                if (detectedSite && !this.hasDetectedSite) {
                  this.hasDetectedSite = true;
                  console.log('[Multi-Site Token Export] 从本地配置检测到站点，将停止循环刷新');
                }
              });
            }
          });
        }, 100); // 只延迟100ms
      }
    });
  }

  handleStatusResponse(response) {
    console.log('[Multi-Site Token Export] 处理状态响应:', response);
    const apiUrl = response.apiUrl || 'http://dev.com/multi-site-token-receiver.php';
    const apiUrlElement = document.getElementById('apiUrl');
    
    // 设置完整URL到title属性
    apiUrlElement.title = apiUrl;
    
    // 显示简化的URL
    if (apiUrl.length > 35) {
      try {
        const url = new URL(apiUrl);
        const domain = url.hostname;
        const path = url.pathname;
        const search = url.search;
        
        // 构建显示字符串
        let displayUrl = domain;
        
        // 添加路径（如果不太长）
        if (path && path !== '/') {
          if (path.length <= 20) {
            displayUrl += path;
          } else {
            displayUrl = path.substring(0, 17) + '...';
          }
        }
        
        // 添加查询参数（如果存在且不太长）
        if (search && search.length <= 15) {
          displayUrl += search;
        }
        
        // 如果总长度仍然太长，进一步截断
        if (displayUrl.length > 35) {
          displayUrl = domain + '/...';
        }
        
        apiUrlElement.textContent = displayUrl;
      } catch (error) {
        // 如果URL解析失败，显示前35个字符
        apiUrlElement.textContent = apiUrl.substring(0, 35) + '...';
      }
    } else {
      apiUrlElement.textContent = apiUrl;
    }
    
    document.getElementById('retryConfig').textContent = `${response.retryCount || 2}次重试，间隔${(response.retryDelay || 3000) / 1000}秒`;
    
    // 只更新状态信息，不重新渲染站点列表
    // 获取当前标签页信息来检测站点
    this.detectCurrentSite(response.sites).then(detectedSite => {
      // 如果检测到具体站点，设置标记并停止循环刷新
      if (detectedSite && !this.hasDetectedSite) {
        this.hasDetectedSite = true;
        console.log('[Multi-Site Token Export] 检测到具体站点，将停止循环刷新');
      }
    });
    
    // 更新站点列表中的时间戳（如果数据包含时间戳）
    if (response.sites) {
      this.updateSiteTimestamps(response.sites);
    }
  }

  updateSiteTimestamps(sites) {
    // 只更新时间戳显示，不重新渲染整个站点列表
    sites.forEach(site => {
      const siteItem = document.querySelector(`[data-domain="${site.site_domain}"]`)?.closest('.site-item');
      if (siteItem) {
        const lastExportElement = siteItem.querySelector('.site-last-export');
        if (lastExportElement) {
          lastExportElement.textContent = `最后导出时间：${this.formatLastExportTime(site.lastExportTime)}`;
        }
      }
    });
  }

  async detectCurrentSiteFromLocalConfig() {
    console.log('[Multi-Site Token Export] 开始从本地配置检测当前站点');
    
    try {
      // 从本地存储获取站点配置
      const sites = await this.configManager.getSites();
      console.log('[Multi-Site Token Export] 从本地配置获取站点列表:', sites);
      
      console.log('[Multi-Site Token Export] 查询当前标签页');
      return new Promise((resolve) => {
        chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
          if (chrome.runtime.lastError) {
            console.error('[Multi-Site Token Export] tabs查询错误:', chrome.runtime.lastError);
            document.getElementById('currentSite').textContent = '权限错误';
            resolve(null);
            return;
          }
          
          if (tabs && tabs[0]) {
            try {
              const url = new URL(tabs[0].url);
              const currentHostname = url.hostname;
              
              const currentSite = sites?.find(site => {
                const exactMatch = currentHostname === site.site_domain;
                const containsMatch = currentHostname.includes(site.site_domain);
                const reverseMatch = site.site_domain.includes(currentHostname);
                return exactMatch || containsMatch || reverseMatch;
              });
              
              if (currentSite) {
                document.getElementById('currentSite').textContent = `${currentSite.site_name} (${currentSite.site_domain})`;
                resolve(currentSite);
              } else {
                document.getElementById('currentSite').textContent = `未配置 (${currentHostname})`;
                resolve(null);
              }
            } catch (error) {
              console.error('[Multi-Site Token Export] 解析URL失败:', error);
              document.getElementById('currentSite').textContent = '无法检测';
              resolve(null);
            }
          } else {
            document.getElementById('currentSite').textContent = '无法获取标签页';
            resolve(null);
          }
        });
      });
    } catch (error) {
      console.error('[Multi-Site Token Export] 从本地配置获取站点失败:', error);
      document.getElementById('currentSite').textContent = '配置错误';
      return null;
    }
  }

  detectCurrentSite(sites) {
    console.log('[Multi-Site Token Export] 开始检测当前站点');
    console.log('[Multi-Site Token Export] 可用站点列表:', sites);
    
    return new Promise((resolve) => {
      chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
        console.log('[Multi-Site Token Export] chrome.tabs.query结果:', tabs);
        console.log('[Multi-Site Token Export] chrome.runtime.lastError:', chrome.runtime.lastError);
        
        if (chrome.runtime.lastError) {
          console.error('[Multi-Site Token Export] tabs查询错误:', chrome.runtime.lastError);
          document.getElementById('currentSite').textContent = '权限错误';
          resolve(false);
          return;
        }
        
        if (tabs && tabs[0]) {
          try {
            console.log('[Multi-Site Token Export] 当前tab:', tabs[0]);
            console.log('[Multi-Site Token Export] 当前tab URL:', tabs[0].url);
            
            const url = new URL(tabs[0].url);
            const currentHostname = url.hostname;
            
            console.log('[Multi-Site Token Export] 当前域名:', currentHostname);
            console.log('[Multi-Site Token Export] 可用站点:', sites);
            
            const currentSite = sites?.find(site => {
              console.log(`[Multi-Site Token Export] 比较: ${currentHostname} vs ${site.site_domain}`);
              // 支持精确匹配和包含匹配
              const exactMatch = currentHostname === site.site_domain;
              const containsMatch = currentHostname.includes(site.site_domain);
              const reverseMatch = site.site_domain.includes(currentHostname);
              
              console.log(`[Multi-Site Token Export] 精确匹配: ${exactMatch}, 包含匹配: ${containsMatch}, 反向匹配: ${reverseMatch}`);
              
              return exactMatch || containsMatch || reverseMatch;
            });
            
            console.log('[Multi-Site Token Export] 匹配结果:', currentSite);
            
            if (currentSite) {
              document.getElementById('currentSite').textContent = `${currentSite.site_name} (${currentSite.site_domain})`;
              resolve(true); // 检测到配置的站点
            } else {
              document.getElementById('currentSite').textContent = `未配置 (${currentHostname})`;
              resolve(false); // 未检测到配置的站点
            }
          } catch (error) {
            console.error('[Multi-Site Token Export] 解析URL失败:', error);
            document.getElementById('currentSite').textContent = '无法检测';
            resolve(false);
          }
        } else {
          console.log('[Multi-Site Token Export] 没有找到活动标签页');
          document.getElementById('currentSite').textContent = '无法获取标签页';
          resolve(false);
        }
      });
    });
  }

  bindEvents() {
    // Tab切换
    document.querySelectorAll('.tab-button').forEach(button => {
      button.addEventListener('click', (e) => this.switchTab(e.target.dataset.tab));
    });
    
    // 其他事件
    document.getElementById('showAddForm').addEventListener('click', () => this.showAddForm());
    document.getElementById('addSite').addEventListener('click', () => this.addSite());
    document.getElementById('testDataExtraction').addEventListener('click', () => this.testDataExtraction());
    document.getElementById('saveConfig').addEventListener('click', () => this.saveConfig());
    document.getElementById('saveEdit').addEventListener('click', () => this.saveEdit());
    document.getElementById('cancelEdit').addEventListener('click', () => this.cancelEdit());
    document.getElementById('debugInfo').addEventListener('click', () => this.showDebugInfo());
  }

  switchTab(tabName) {
    // 移除所有active类
    document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
    document.querySelectorAll('.tab-panel').forEach(panel => panel.classList.remove('active'));
    
    // 激活选中的tab
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
    document.getElementById(`${tabName}-tab`).classList.add('active');
  }

  formatLastExportTime(timestamp) {
    console.log('[Multi-Site Token Export] 格式化时间戳:', timestamp);
    if (!timestamp) {
      return '从未导出';
    }
    
    const now = new Date();
    const exportTime = new Date(timestamp);
    const diffMs = now - exportTime;
    const diffSeconds = Math.floor(diffMs / 1000);
    const diffMinutes = Math.floor(diffSeconds / 60);
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);
    
    console.log('[Multi-Site Token Export] 时间差:', diffMs, 'ms,', diffSeconds, '秒');
    
    if (diffSeconds < 60) {
      return `${diffSeconds}秒前`;
    } else if (diffMinutes < 60) {
      return `${diffMinutes}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return exportTime.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  }

  showDebugInfo() {
    chrome.runtime.sendMessage({ action: 'getStatus' }, (response) => {
      if (response) {
        const debugInfo = {
          '当前时间': new Date().toISOString(),
          'API地址': response.apiUrl,
          '站点数量': response.sites ? response.sites.length : 0,
          '站点详情': response.sites ? response.sites.map(site => ({
            '站点名称': site.site_name,
            '域名': site.site_domain,
            '最后导出时间戳': site.lastExportTime,
            '格式化时间': this.formatLastExportTime(site.lastExportTime),
            '最后Token': site.lastToken
          })) : []
        };
        
        const debugText = JSON.stringify(debugInfo, null, 2);
        alert('调试信息：\n\n' + debugText);
        console.log('[Multi-Site Token Export] 调试信息:', debugInfo);
      } else {
        alert('无法获取调试信息');
      }
    });
  }

  // 停止定期刷新
  stopPeriodicRefresh() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
      this.refreshInterval = null;
      console.log('[Multi-Site Token Export] 定期刷新已停止');
    }
  }

  // 清理资源
  destroy() {
    this.stopPeriodicRefresh();
  }
}

// 启动
console.log('[Multi-Site Token Export] Popup脚本开始执行');
const popupManager = new MultiSitePopupManager();
console.log('[Multi-Site Token Export] Popup管理器已创建');